import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/views/Home.vue'
// import Consult from '@/views/Consult.vue'
// import Cases from '@/views/Cases.vue'
// import Lawyers from '@/views/Lawyers.vue'
// import Resources from '@/views/Resources.vue'
// import About from '@/views/About.vue'
// import Civil from '@/views/Civil.vue'
// import Criminal from '@/views/Criminal.vue'
// import Administrative from '@/views/Administrative.vue'
import Main from '@/views/Main.vue'
import NotFound from '@/views/NotFound.vue'
// import CaseApplication from '@/views/CaseApplication.vue'
import Login from '@/views/login/index.vue'
import { useAuthStore } from '@/stores/authStore'
import { generateDynamicRoutes } from "./dynamicRoutes.js";

const routes = [
  {
    path: '/',
    component: Main,
    name: 'Main',
    redirect: '/home',
    meta: { requiresAuth: true },
    children: [
      { path: '/home', name: 'Home', component: Home },
      // {path: '/consult',name: 'Consult',component: Consult},
      // {path: '/cases',name: 'Cases',component: Cases},
      // {path: '/lawyers',name: 'Lawyers',component: Lawyers},
      // {path: '/resources',name: 'Resources',component: Resources},
      // {path: '/about',name: 'About',component: About},
      // {path: '/resources/civil',name: 'Civil',component: Civil},
      // {path: '/resources/criminal',name: 'Criminal',component: Criminal},
      // {path: '/resources/administrative',name: 'Administrative',component: Administrative},
      // {path: '/application',name: 'CaseApplication',component: CaseApplication}
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/:pathMatch(.*)*', // 404 路由捕获
    name: 'NotFound',
    component: NotFound
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore();
  const requiresAuth = to.matched.some(record => record.meta?.requiresAuth);

  //判断用户是否已经加载动态路由
  if (authStore.isLoggedIn() && !authStore.hasLoadedDynamicRoutes) {
    console.log('用户已经登录，加载动态路由')
    // 加载动态路由
    addRoutes(authStore.menuList)
    // console.log(routes)
    authStore.hasLoadedDynamicRoutes = true
    return next({ path: to.fullPath, replace: true })
  }
  if (requiresAuth && !authStore.isLoggedIn()) {
    next('/login'); // 未登录，重定向到登录页
  } else {
    next(); // 已登录，继续导航
  }
})

export function addRoutes(menuList) {
  const newRoutes = generateDynamicRoutes(menuList)
  // console.log(newRoutes);
  newRoutes.forEach(route => {
    router.addRoute('Main', route);
  });
}


export default router